<?php

//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                               |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: xiangminghu@clcw.com.cn                                        |
// +------------------------------------------------------------------------+
//

namespace AuctionBack\Controller;

use AuctionCore\Account\Back\Employee;
use AuctionCore\AuctionOrder\Consult;
use AuctionCore\AuctionOrder\AuOrder;
use AuctionCore\AuctionOrder\Recheck;
use AuctionCore\CarDealer\AssetCenter;
use AuctionCore\CarResource\Car;
use AuctionCore\CarOwner\Owner;
use AuctionCore\AuctionOrder\CarReturn;
use AuctionCore\Fours\Fours;
use AuctionCore\AuctionOrder\Scene;
use AuctionCore\PurchaseOrder\PurchaseOrder;
use AuctionCore\Cashier\Payment as CashierPayment;
use AuctionCore\System\AuctionException;
use AuctionCore\CarResource\CarSource;
use AuctionBack\Logic\CarReportLogic;

/**
 * 双方磋商
 *
 * @author Xmh
 */
class ConsultController extends BaseController
{
    private $Consult;
    private $emp_id;

    public function __construct()
    {
        parent::__construct();
        $this->Consult = new Consult();
        $this->emp_id = $this->user_info['emp_id'];
        //模板赋值
        $this->assign("emp_id", $this->emp_id);
    }

    public function index()
    {
        $branch_id = $this->user_info['branch_id'];
        //分公司列表
        $bc_list = $this->get_branch_company_list();
        $this->assign('bc_list', $bc_list);
        $this->assign('branch_id', $branch_id);

        $channel = new \AuctionCore\Other\Channel();
        $pfrom = $channel->get_parent_channel_list();
        $comefrom_list = $this->get_comefrom_list();
        //城市对应的4s店
        $city_fours_list = $this->get_fours_by_city();
        $this->assign("pfrom", $pfrom);
        $this->assign('comefrom_list', $comefrom_list);
        $this->assign('city_fours_list', $city_fours_list);
        $this->display();
    }

    /**
     * 获取列表
     */
    public function consult_list()
    {
        $page = I("get.p", 1);
        $size = 10;
        $params = array();
        $params['status'] = I('get.status');
        $params['trace_start_time'] = I('get.trace_start_time'); //跟踪开始时间
        $params['trace_end_time'] = I('get.trace_end_time'); //跟踪结束时间
        $params['consult_start_time'] = I('get.consult_start_time'); //预约开始时间
        $params['consult_end_time'] = I('get.consult_end_time'); //预约结束时间
        $params['location_area'] = I('get.location_area'); //所在地
        $params['comefrom'] = I('get.comefrom'); //渠道来源
        $params['order_no'] = I('get.order_no');

        //所在地查询
        if (count($this->bc_city) > 1) {
            $bc_code = array_flip($this->bc_city);
            $bc_code = implode(',', $bc_code);
            $params['bc_city'] = $bc_code;
        }
        $params['emp_id'] = $this->emp_id;
        //检查权限
        $rules = "ShuangFangCuoShangChaKanSuoYou";
        $e = new Employee($this->user_info['username']);
        $auth = $e->check_auth($rules);
        $params['auth'] = $auth;

        //检查分配权限
        $fenpei_rules = "ShuangFangCuoShangFenPei";
        $fenpei_auth = $e->check_auth($fenpei_rules);
        $params['fenpei_auth'] = $fenpei_auth;
        //获取客服
        if ($fenpei_auth) {
            $kefu_list = Employee::get_branch_emp(C('OWNER_CONSULT_SERVER.0'));
            $this->assign('kfs', $kefu_list);
        }
        $result = $this->Consult->get_consult_list($page, $size, $params);
        $list = empty($result['list']) ? array() : $result['list'];
        //分页
        $Page = new \AuctionCore\Common\AjaxPage($result['total'], $size, "get_page");
        $Page->setConfig('theme', " %totalRow% %header% %nowPage%/%totalPage% 页 %first% %upPage% %prePage% %linkPage% %nextPage% %downPage%  %end% %jumpform%");
//        dump($list);
        $show = $Page->show();          // 分页显示输出
        $this->assign('page', $show);   // 赋值分页输出
        $this->assign('list', $list);
        $this->assign('p', $page);
        $this->assign('params', $params);
        $this->display();
    }

    /**
     * 检查磋商拍单是否已被跟踪
     *
     * @param      $consult_id
     * @param      $consult_status
     * @param bool $return
     *
     * @return \AuctionCore\AuctionOrder\multitype
     */
    public function is_consult_assigned($consult_id, $consult_status, $return = false)
    {
        $consult_id = $consult_id ? $consult_id : I('get.consult_id/d', 0);
        $consult_status = $consult_status ? $consult_status : I('get.consult_status/d', 0);
        //判断拍单是否被跟踪
        $code = '200';
        $msg = 'SUCCESS';
        $redirect_url = U('Consult/consult_deal', ['status' => $consult_status, 'id' => $consult_id]);
        try {
            $consult_detail = $this->Consult->consult_detail($consult_id);
        } catch (AuctionException $e) {
            $code = $e->getCode();
            $msg = $e->getMessage();
        }

        if ($consult_detail['emp_id'] > 0 && $consult_detail['emp_id'] != $this->emp_id) {  //分配此单给客户
            $this->helpJsonResult('526', '此信息正在被其他人使用');
            exit;
        }
        if ($consult_detail['emp_id'] == '0') {//尚未分配
            //分配此单给客户
            $consult_data = ['id' => $consult_id, 'consult_status' => 2, 'emp_id' => $this->emp_id];
            $this->Consult->update_consult($consult_data);
            //双方磋商跟踪日志
            $consult_trace_log = array(
                'order_id' => $consult_detail['order_id'],
                'emp_id' => $this->emp_id,
                'action' => '跟踪分配',
                'type' => 2,
                'result' => '跟踪分配',
            );
            $this->Consult->add_consult_trace_log($consult_trace_log);
            $log = array('consult_id' => $consult_id, 'emp_id' => $this->emp_id, 'action' => '系统分配双方磋商拍单。' . $msg);
            \AuctionCore\System\SystemLog::add($log);
        }
        if (!$return) {
            $this->helpJsonResult($code, $msg, $redirect_url);
            exit;
        }
        return $consult_detail;
    }

    //分配客服
    public function assignServer()
    {
        $consult_id = I('post.consult_id/d', '');
        if (empty($consult_id)) {
            $this->helpJsonResult(400, "磋商信息错误!");
        }
        $service_id = I('post.service_id/d', '');
        if (empty($service_id)) {
            $this->helpJsonResult(400, "请选择客服");
        }
        $consult_detail = $this->Consult->consult_detail($consult_id);
        if (empty($consult_detail)) {
            $this->helpJsonResult(404, "磋商信息不存在");
        }

        if ($consult_detail['emp_id'] == $service_id) {
            $this->helpJsonResult(400, "不能分配给同一个人，请重新选择");
        }

        $consult_data = [
            'id' => $consult_id,
            'emp_id' => $service_id
        ];
        $ok = $this->Consult->update_consult($consult_data);
        if (!$ok) {
            $this->helpJsonResult(500, " 分配失败,请稍后再试 ");
        }
        //双方磋商跟踪日志
        $consult_trace_log = array(
            'order_id' => $consult_detail['order_id'],
            'emp_id' => $this->emp_id,
            'action' => '分配客服',
            'type' => 2,
            'result' => '分配客服',
        );
        $this->Consult->add_consult_trace_log($consult_trace_log);


        /**
         * 记录车辆跟踪日志
         */
        $car_action_data = array(
            'action_name' => "双方磋商，跟踪分配",
            'emp_id' => $this->emp_id
        );
        \AuctionCore\CarResource\Car::add_car_trace_log($consult_detail['car_id'], $car_action_data);
        /**
         * 记录拍品跟踪日志
         */
        $order_action_data = array(
            'action_name' => "双方磋商，跟踪分配",
            'emp_id' => $this->emp_id
        );
        \AuctionCore\AuctionOrder\AuOrder::add_order_trace_log($consult_detail['order_id'], $order_action_data);
        $this->helpJsonResult(200, "分配成功");
    }

    //处理双方磋商页面
    public function consult_deal()
    {
        $consult_id = I('get.id/d', 0);
        $consult_status = I('get.status/d', 0);
        $consult_detail = $this->Consult->consult_detail($consult_id);
        $consult_status = $consult_detail['consult_status'];
        if ($consult_status > 2 || empty($consult_status)) {
            $this->redirect('Consult/index', '', 1, '请求出错了');
        }

        $car_detail = \AuctionCore\CarResource\Car::getDetailWithChannel($consult_detail['car_id']);

        $this->assign('car_detail', $car_detail);

        $show_from = \AuctionCore\Other\Channel::get_from();  //获取渠道来源信息
        $this->assign('show_from', $show_from);

        $transfer_type = C('TRANSFER_LIMIT');
        $this->assign('transfer_type', $transfer_type);

        $store = new \AuctionCore\Other\Store();
        $map = array();
        $map['status'] = array('eq', 0);
        $map['type'] = 3; //交付店
        if ($this->is_hq == false) {
            $map['city'] = ['in', $this->user_info['bc_code']];
        }
        $stores = $store->get_stores($map);
        $this->assign('stores', $stores);
        $this->assign('rank_data', $consult_detail['rank_data']);
        $this->assign('detail', $consult_detail);
        $this->assign('status', $consult_status);
        //双方磋商跟踪日志
        $consult_trace_log = $this->Consult->get_consult_trace_log($consult_detail['order_id']);
        $this->assign('consult_trace_log', $consult_trace_log);

        $scene = new \AuctionCore\AuctionOrder\Scene();
        $scene_detail = $scene->detail($consult_detail['scene_id']);
        $starttime = $scene_detail['starttime'];

        //获取交易服务费
        $row = M('setting')->where(array('name' => 'COMMISION_MIN_FEE'))->find();
        $arr = json_decode($row['remark'], true);
        if ($arr['is_avalible'] == '1') {
            if (date('Y-m-d', strtotime($starttime)) == $arr['startdate']) {
                $min_fee = $arr['commision'];
            } else {
                $min_fee = $row['value'];
            }
        } else {
            $min_fee = $row['value'];
        }
        $min_fee = intval($min_fee);
        $max_fee = M('setting')->where(array('name' => 'COMMISION_MAX_FEE'))->getField('value');
        $max_fee = intval($max_fee);

        $percentage = M('setting')->where(array('name' => 'COMMISION_PERCENTAGE'))->getField('value');
        $percentage = floatval($percentage);
        $this->assign('min_fee', $min_fee);
        $this->assign('max_fee', $max_fee);
        $this->assign('percentage', $percentage);
        //打款帐号
        $fours = new Fours();
        $fours_detail = $fours->get_fours_info(['channel_id' => $car_detail['comefrom']]);
        $fours_bank_account = $fours->get_bank_account_list_by_fid($fours_detail['fid']);
        $fours_bank_account_total = count($fours_bank_account);
        $this->assign('fours_bank_account', $fours_bank_account);
        $this->assign('fours_bank_account_total', $fours_bank_account_total);
        $this->display();
    }

    //处理双方磋商操作
    public function do_consult_deal()
    {
        $consult_id = I('post.consult_id');
        $order_id = I('post.order_id/d', 0);
        $owner_id = I('post.owner_id/d', 0);
        $dealer_id = I('post.dealer_id/d', 0);
        $consult_increase = I('post.fare'); //第一名加价
        $company_subsidies = I('post.subsidy'); //公司补贴
        $car_source = I('post.car_source');
        $consult_remark = I('post.consult_remark');
        $bank_name = I('post.bank_name');
        $card_no = I('post.card_no');
        $account_name = I('post.account_name');


        if ($car_source == 2) {       //个人才有签约
            $service_method = I('post.service_method');
            $reserve_store = I('post.reserve_store');
            $reserve_time = I('post.reserve_time');
            $reserve_time = transform_date($reserve_time, 2);
            if (!$reserve_time) {
                $this->helpJsonResult(500, "预约时间不能为空");
            }
            if (!$service_method) {
                $this->helpJsonResult(500, "服务方式不能为空");
            }
            if ($service_method == 2) {
                $reserve_province = I('post.reserve_province');
                $reserve_city = I('post.reserve_city');
                $reserve_area = I('post.reserve_area');
                $reserve_address = I('post.reserve_address');
                if (!$reserve_province) {
                    $this->helpJsonResult(500, "预约省份不能为空");
                }
                if (!$reserve_city) {
                    $this->helpJsonResult(500, "预约城市不能为空");
                }
                if (!$reserve_area) {
                    $this->helpJsonResult(500, "预约地区不能为空");
                }
                if (!$reserve_address) {
                    $this->helpJsonResult(500, "预约详细地址不能为空");
                }
            } elseif ($service_method == 3) {
                if (!$reserve_store) {
                    $this->helpJsonResult(500, "请选择预约门店");
                }
            } else {
                $this->helpJsonResult(500, "请选择正确的服务方式");
            }
            //更新车主表，填写预约信息
            $owner_data = array();
            $owner_data['sign_reserve_time'] = $reserve_time;
            $owner_data['sign_service_method'] = $service_method;
            if ($service_method == 2) {
                $owner_data['sign_reserve_province'] = $reserve_province;
                $owner_data['sign_reserve_city'] = $reserve_city;
                $owner_data['sign_reserve_area'] = $reserve_area;
                $owner_data['sign_reserve_address'] = $reserve_address;
            }
            $owner_data['sign_reserve_store'] = $reserve_store;
            $owner_data['sign_next_trace_time'] = $reserve_time; //下次跟踪时间
            $owner = new Owner($owner_id);
            $owner->update($owner_data);

            //记录下次跟踪日志
            $data = array();
            $data['order_id'] = $order_id;
            $data['owner_id'] = $owner_id;
            $data['service_id'] = $this->emp_id;
            $data['reserve_time'] = $reserve_time;
            $data['service_method'] = $service_method;
            $data['province'] = $reserve_province;
            $data['city'] = $reserve_city;
            $data['area'] = $reserve_area;
            $data['address'] = $reserve_address;
            $data['next_trace_time'] = $reserve_time;
            $data['remark'] = $consult_remark;
            $data['result'] = 4; //磋商成功
            try {
                $owner->confirm_trace_log($data);
            } catch (AuctionException $e) {
                $this->helpJsonResult($e->getCode(), $e->getMessage());
            }
        }
        //数据验证
        if (!$order_id) {
            $this->helpJsonResult(500, "拍单ID不能为空");
        }
        $order = new AuOrder($order_id);
        $order_detail = $order->detail();
        if (empty($order_detail)) {
            $this->helpJsonResult(500, "未找到拍单信息");
        }
        //找不到车商 建议重拍
        if ($order_detail['bidding_best_price'] == 0 && $order_detail['bid_best_price'] == 0) {
            $this->helpJsonResult(500, '此车辆无车商出价建议重拍！');
        }
        $bidding_best_price = $order_detail['bidding_best_price'] > $order_detail['bid_best_price'] ?
            $order_detail['bidding_best_price'] : $order_detail['bid_best_price'];
        $success_price = $bidding_best_price + $consult_increase;
        if (!$owner_id) {
            $this->helpJsonResult(500, "车主ID不能为空");
        }
        $car = new \AuctionCore\CarResource\Car($order_detail['car_id']);
        $car_detail = $car->detail();
        //获取场次开始时间
        $scene = new \AuctionCore\AuctionOrder\Scene();
        $scene_detail = $scene->detail($order_detail['scene_id']);
        $starttime = $scene_detail['starttime'];

        $purchaseOrderArr = [
            'order_id' => $order_id,
            'order_no' => $order_detail['order_no'],
            'car_id' => $order_detail['car_id'],
            'sid' => $car_detail['sid'],
            'amount' => $success_price + $company_subsidies, //主成交价 = 拍卖最高价 + 公司补贴
            'emp_id' => $this->emp_id,
            'type' => $car_detail['is_self_receive'] ? '2' : '1', //判断是否自收车
            'status' => '1',
            'createtime' => date('Y-m-d H:i:s', time()),
        ];

        $paymentData['bank_name'] = $bank_name;
        $paymentData['card_no'] = $card_no;
        $paymentData['account_name'] = $account_name;
        $carReport = new CarReportLogic($car_detail['car_id']);
        $branchId = $carReport->getBranchId();
        $paymentData['branch_id'] = $branchId;
        //更新拍单状态，记录磋商加价、公司补贴、成交价格
        $orderData = array();
        $orderData['is_consult'] = 1;
        $orderData['consult_increase'] = $consult_increase;
        $orderData['company_subsidies'] = $company_subsidies;
        $orderData['success_price'] = $success_price;
        $orderData['commision'] = get_commision($success_price, $starttime);
        //更新竞拍最高价或投标最高价
        if ($order_detail['bidding_best_price'] > $order_detail['bid_best_price']) {
            $orderData['bidding_best_price'] = $success_price;
        } else {
            $orderData['bid_best_price'] = $success_price;
        }
        if ($car_detail['car_source'] == 1) { //4S店车源无需签约,付全款
            $orderData['status'] = 8;
            $orderData['first_money'] = $success_price + $company_subsidies;
            $orderData['return_check_status'] = 1; //待回车
        } else {
            $orderData['status'] = 7; //已确认
            $orderData['return_check_status'] = 3;//待复检
        }
        //启动事务
        M()->startTrans();
        $order_res = $order->update($orderData);
        //更新车辆信息
        $car_data = [];
        $car_data['success_price'] = $success_price;
        if ($car_detail['car_source'] == 1) { //4S店车源
            //添加回车信息
            $res4 = CarReturn::create([
                'order_id' => $order_id,
                'sid' => $car_detail['sid'],
                'car_id' => $car_detail['car_id']
            ]);
            if (!$res4) {
                M()->rollback();
                $this->helpJsonResult(500, "添加回车信息失败");
            }
            //4s店车源添加检测费
            //$car_data['check_fee'] = $check_fee_conf['value'];
            $car_data['pay_status'] = 1;
            $sid = $car_detail['sid'];
            $purchaseOrderObj = new PurchaseOrder();
            //判断是不是有采购单
            $purchaseOrderData = $purchaseOrderObj->viewBySid($sid);
            //如果没有，采购单就加入
            if (empty($purchaseOrderData)) {
                $res5 = $this->addPurchaseOrder($purchaseOrderArr); //添加采购单
                if (!$res5) {
                    M()->rollback();
                    $this->helpJsonResult(500, "添加采购单信息失败");
                }
                $paymentData['amount'] = $success_price + $company_subsidies; //4s 店全款 车主成交价 = 拍卖最高价 + 公司补贴
                $paymentData['pay_type'] = 1;
                $res6 = $this->generatorPayment($paymentData);//添加付款单

                $res7 = $this->addPaymentRelation($res5, $res6, $paymentData['pay_type']);

                if (!$res7) {
                    M()->rollback();
                    $this->helpJsonResult(500, "生成付款单关系数据失败");
                }
            }
        } else {
            //个人车源添加复检信息
            $res4 = Recheck::create([
                'order_id' => $order_id,
                'sid' => $car_detail['sid'],
                'car_id' => $car_detail['car_id']
            ]);
            if (!$res4) {
                M()->rollback();
                $this->helpJsonResult(500, "添加复检信息失败");
            }
        }
        //更新车源成交价
        $car_res = $car->update($car_data);
        $consult_data = array();
        $consult_data['id'] = $consult_id;
        $consult_data['emp_id'] = $this->emp_id;
        $consult_data['consult_status'] = 4; //磋商成功
        $consult_data['consult_remark'] = $consult_remark;
        $consult_data['updatetime'] = date("Y-m-d H:i:s", time());
        $consult_data_res = $this->Consult->update_consult($consult_data);
        if (!$order_res || !$consult_data_res || !$car_res) {
            M()->rollback();
            $this->helpJsonResult(500, '确认失败或已确认,数据未更新');
        }
        //事务提交
        M()->commit();
        //更新车源状态
        $CarSource = new CarSource($car_detail['sid']);
        $CarSourceInfo = $CarSource->getInfo();
        if ($CarSourceInfo['status'] < 400) {
            $csData = [];
            $csData['status'] = 400;
            $CarSource->update($csData);
        }
        //过户费
        if ($order_detail['transfer_type'] == 1) {
            //车商自过 没有过户费
            $transfer_fee = 0;
        } else {
            $transfer_fee = $order_detail['transfer_fee'];
        }
        //场次活动
        $activity_reduction = 0;
        $res_activity = Scene::is_scene_activity($order_detail['scene_id']);
        if (!empty($res_activity)) {
            //根据场次活动减免规则id找到减免规则
            foreach ($res_activity as $k => $v) {
                if ($v['rules_type'] == 2) {
                    //如果减免规则的rules_type == 2 说明是阶梯立减 去activity_rules表中找到相应的详细规则
                    $activity_reduction = Scene::get_activity_rules_price($v['scene_activity_id'], $success_price);
                } elseif ($v['rules_type'] == 1) {
                    //如果减免规则rules_type == 1 说明是活动统一立减,取出scene_activity['amount'] 即可
                    $activity_reduction = $v['amount'];
                }
            }
        } else {
            $activity_reduction = 0; //判断如果没有活动减免价格 则设置scene_activity_amount的值为0;
        }
        $final_price = $success_price - $activity_reduction + $order_detail['commision'] + $transfer_fee;
        $orderFee = [
            'success_price' => $success_price,
            'commision' => $orderData['commision'],
            'transfer_fee' => $transfer_fee,
            'final_price' => $final_price,
            'activity_reduction' => $activity_reduction
        ];
        $order->addOrderFee($orderFee);

        //第一名加价则插入拍卖出价记录
        if ($consult_increase > 0) {
            //竞标价大于投标价
            if ($order_detail['bidding_best_price'] > $order_detail['bid_best_price']) {
                $bidding_log_data = array();
                $bidding_log_data['dealer_id'] = $dealer_id;
                $bidding_log_data['order_id'] = $order_id;
                $bidding_log_data['bidding_type'] = 1;
                $bidding_log_data['before_price'] = $bidding_best_price;
                $bidding_log_data['append_price'] = $consult_increase;
                $bidding_log_data['after_price'] = $success_price;
                $bidding_log_data['createtime'] = date("Y-m-d H:i:s", time());
                $order->add_bidding_log($bidding_log_data);
            } else {
                $bid_log_data = array();
                $bid_log_data['dealer_id'] = $dealer_id;
                $bid_log_data['order_id'] = $order_id;
                $bid_log_data['bid_type'] = 1;
                $bid_log_data['price'] = $success_price;
                $bid_log_data['createtime'] = date("Y-m-d H:i:s", time());
                $order->add_bid_log($bid_log_data);
            }
        }

        //双方磋商跟踪日志
        $consult_trace_log = array(
            'order_id' => $order_id,
            'emp_id' => $this->emp_id,
            'action' => '磋商成功',
            'type' => 1,
            'result' => $consult_remark,
        );
        $this->Consult->add_consult_trace_log($consult_trace_log);

        //记录车辆全局跟踪日志
        $log = array(
            'emp_id' => $this->emp_id,
            'order_id' => $order_id,
            'car_id' => $car_detail['car_id'],
            'owner_id' => $owner_id,
            'result' => '磋商成功'
        );
        \AuctionCore\System\GlobalLog::add($log);

        /**
         * 记录车辆跟踪日志
         */
        $car_action_data = array(
            'action_name' => "双方磋商，成功",
            'emp_id' => $this->emp_id
        );
        \AuctionCore\CarResource\Car::add_car_trace_log($car_detail['car_id'], $car_action_data);
        /**
         * 记录拍品跟踪日志
         */
        $order_action_data = array(
            'action_name' => "双方磋商，成功",
            'emp_id' => $this->emp_id
        );
        \AuctionCore\AuctionOrder\AuOrder::add_order_trace_log($order_id, $order_action_data);


        //自收车辆则不发卡券
        if ($car_detail['is_self_receive'] != 1) {
            //发放抽奖卡券
            $Raffle = new \AuctionCore\Other\Raffle();
            $is_raffle = $Raffle->order_binding_card($order_id, 1);
            if ($is_raffle['is_bool'] > 0) {
                $raffle_log = ['emp_id' => $this->emp_id, 'order_id' => $order_id, 'lottery_id' => $is_raffle['cid']];
                $Raffle::grant_lottery_log($raffle_log);
            }

            //发放抽代金券卡券
            $is_coupon = $Raffle->order_binding_card($order_id, 2);
            if ($is_coupon['is_bool'] > 0) {
                $coupon_log = ['emp_id' => $this->emp_id, 'order_id' => $order_id, 'lottery_id' => $is_coupon['cid']];
                $Raffle::grant_lottery_log($coupon_log);
            }
        }
        //记录员工操作日志
        $log = array(
            'emp_id' => $this->emp_id,
            'order_id' => $order_id,
            'car_id' => $car_detail['car_id'],
            'owner_id' => $owner_id,
            'action' => '磋商成功');
        \AuctionCore\System\SystemLog::add($log);
        //输出json格式处理结果
        $this->helpJsonResult(200, "操作成功");
    }

    /**
     * 添加采购单
     *
     * @param array $data 采购单数据
     * @return mixed 返回添加结果
     */
    public function addPurchaseOrder($data)
    {
        $obj = new PurchaseOrder();
        $purchaseOrderType = $data['type'];
        $data['purchase_order_nu'] = $obj->generatePurchaseOrderNu($purchaseOrderType);
        return $obj->add($data);
    }


    /**
     *  生成付款单
     *
     * @param array $paymentData 付款单数据
     * @return mixed
     */
    public function generatorPayment($paymentData)
    {
        $paymentData['pay_way'] = 2;// 现金
        $paymentData['create_time'] = date('Y-m-d H:i:s');//创建时间
        $result = CashierPayment::add($paymentData);
        return $result;
    }

    /**
     * 添加采购单付款关系数据
     *
     * @param int $purchaseOrderId 采购单编号
     * @param int $paymentId 付款单编号
     * @param int $paymentType 付款类型
     * @return mixed
     */
    public function addPaymentRelation($purchaseOrderId, $paymentId, $paymentType)
    {
        $purchaseOrder = new PurchaseOrder();
        return $purchaseOrder->addPaymentAndPurchaseOrderRelation($purchaseOrderId, $paymentId, $paymentType);
    }

    //处理直接重拍
    public function do_reauction()
    {
        //获取外部数据
        $consult_id = I('post.consult_id');
        $order_id = I('post.order_id');
        $owner_id = I('post.owner_id');
        $reserve_price = I('post.reserve_price');
        $last_transfer_limit = I('post.last_transfer_limit');
        $transfer_limit = I('post.transfer_limit');
        $remark_fail = urldecode(I('post.remark'));
        //数据验证
        if (!$order_id) {
            $this->helpJsonResult(400, "拍单ID不能为空");
        }
        $order = new AuOrder($order_id);
        $order_detail = $order->detail();
        if (empty($order_detail)) {
            $this->helpJsonResult(400, "未找到拍单信息");
        }
        //检查前置状态
        if ($order_detail['status'] != 5) {
            $this->helpJsonResult(400, "拍单状态异常,请联系管理员");
        }
        if (!$owner_id) {
            $this->helpJsonResult(400, "车主ID不能为空");
        }
        if (!$reserve_price) {
            $this->helpJsonResult(400, "保留价不能为空");
        }
        if (!is_numeric($reserve_price)) {
            $this->helpJsonResult(400, "保留价输入错误");
        }
        $car = new Car($order_detail['car_id']);
        $car_detail = $car->detail();
        /*$post_date = strtotime($car_detail['posttime']);
        $now_date = time();
        if (($now_date - $post_date) > 60 * 60 * 24 * 4) {
            $this->helpJsonResult('518', '报告已失效，请重新上传报告');
        }*/

        //开启事务
        M()->startTrans();
        //拍单状态失败,失败类型为车主要求重拍，记录备注
        $res = $order->update(array(
            'status' => 12,
            'fail_type' => 1,
            'remark_fail' => $remark_fail
        ));

        //更改车源状态为7（待重拍）
        //car_status 7 待重拍,re_auction_type 1 未过保留价重拍 2车商违约重拍 3磋商失败96小时内可重拍
        $car_data = array();
        $car_data['re_auction_reason'] = $remark_fail;
        $car_data['transfer_limit'] = $transfer_limit;
        $car_data['car_status'] = '7';
        $car_data['re_auction_type'] = 3;
        $car_data['is_self_receive'] = 0;

        //保留价更改
        if ($car_detail['reserve_price'] != $reserve_price) {
            $car_data['reserve_price'] = $reserve_price;
            //记录修改历史
            $reserve_price_history = json_decode($car_detail['reserve_price_history']);
            array_push($reserve_price_history, array(
                'price' => $reserve_price,
                'name' => $this->user_info['real_name'],
                'id' => $this->user_info['emp_id'],
                'time' => date("Y-m-d H:i:s")
            ));
            $car_data['reserve_price_history'] = json_encode($reserve_price_history, JSON_UNESCAPED_UNICODE);
        }
        $res1 = $car->update($car_data);

        //插入跟踪日志
        $owner = new Owner($owner_id);
        $res2 = $owner->confirm_trace_log([
            'order_id' => $order_id,
            'owner_id' => $owner_id,
            'service_id' => $this->emp_id,
            'remark' => trim($remark_fail),
            'result' => 5,
        ]);

        //更新consult
        $consult_data = array();
        $consult_data['id'] = $consult_id;
        $consult_data['emp_id'] = $this->emp_id;
        $consult_data['consult_status'] = 3; //重拍
        $consult_data['consult_remark'] = $remark_fail;
        $consult_data['updatetime'] = date("Y-m-d H:i:s", time());
        $res3 = $this->Consult->update_consult($consult_data);

        $CarSource = new CarSource($car_detail['sid']);
        $CarSourceInfo = $CarSource->getInfo();
        $res_cs = true;
        if ($CarSourceInfo['status'] < 400) {
            $csData = [];
            $csData['status'] = 100;
            $res_cs = $CarSource->update($csData);
        }


        if (!$res || !$res1 || !$res2 || !$res3 || !$res_cs) {
            M()->rollback();
            $this->helpJsonResult(500, "操作失败或数据已更新未改变");
        }
        //提交事务
        M()->commit();


        //双方磋商跟踪日志
        $consult_trace_log = array(
            'order_id' => $order_id,
            'emp_id' => $this->emp_id,
            'action' => '重拍',
            'type' => 2,
            'result' => $remark_fail,
        );
        $this->Consult->add_consult_trace_log($consult_trace_log);

        //记录车主确认的拍单重拍记录
        $owner_remake_log = array(
            'emp_id' => $this->emp_id,
            'owner_id' => $owner_id,
            'car_id' => $car_detail['car_id'],
            'order_id' => $order_id,
            'reserve_price' => $reserve_price,
            'last_transfer_limit' => $last_transfer_limit,
            'transfer_limit' => $transfer_limit,
            'remark' => $remark_fail
        );
        \AuctionCore\AuctionOrder\AuOrder::add_owner_remake_log($owner_remake_log);
        //记录车辆全局跟踪日志
        $log = array(
            'emp_id' => $this->emp_id,
            'order_id' => $order_id,
            'car_id' => $order_detail['car_id'],
            'owner_id' => $owner_id,
            'result' => '双方磋商车辆重拍');
        \AuctionCore\System\GlobalLog::add($log);

        //记录车辆跟踪日志
        $car_action_data = array(
            'action_name' => "双方磋商，重拍",
            'emp_id' => $this->emp_id
        );
        \AuctionCore\CarResource\Car::add_car_trace_log($order_detail['car_id'], $car_action_data);

        //记录拍品跟踪日志
        $order_action_data = array(
            'action_name' => "双方磋商，重拍",
            'emp_id' => $this->emp_id
        );
        \AuctionCore\AuctionOrder\AuOrder::add_order_trace_log($order_id, $order_action_data);

        //解冻车商保证金
        AssetCenter::free_all($order_id);

        //记录员工操作日志
        $log = array(
            'emp_id' => $this->emp_id,
            'order_id' => $order_id,
            'car_id' => $order_detail['car_id'],
            'owner_id' => $owner_id,
            'action' => '重拍车源'
        );
        \AuctionCore\System\SystemLog::add($log);
        $this->helpJsonResult(200, "操作成功");
    }

    /**
     * 磋商失败重拍
     */
    public function re_auction()
    {
        //获取外部数据
        $order_id = I('post.order_id');
        $owner_id = I('post.owner_id');
        $reserve_price = I('post.reserve_price');
        $remark_fail = urldecode(I('post.remark'));
        $last_transfer_limit = I('post.last_transfer_limit');
        $transfer_limit = I('post.transfer_limit');
        //数据验证
        if (!$order_id) {
            $this->helpJsonResult(400, "拍单ID不能为空");
        }
        //验证拍单信息
        $order = new AuOrder($order_id);
        $order_detail = $order->detail();
        if (empty($order_detail)) {
            $this->helpJsonResult(400, "未找到拍单信息");
        }
        if (!$owner_id) {
            $this->helpJsonResult(400, "车主ID不能为空");
        }
        if (!$reserve_price) {
            $this->helpJsonResult(400, "保留价不能为空");
        }
        if (!is_numeric($reserve_price)) {
            $this->helpJsonResult(400, "保留价输入错误");
        }
        $car = new Car($order_detail['car_id']);
        $car_detail = $car->detail();

        if ($car_detail['car_status'] != 8) {
            $this->helpJsonResult('519', '车辆已重拍');
        }

        /*$post_date = strtotime($car_detail['posttime']);
        $now_date = time();
        if (($now_date - $post_date) > 60 * 60 * 24 * 4) {
            $this->helpJsonResult('518', '报告已失效，请重新上传报告');
        }*/
        $carData = array();
        $orderData = array();
        $carData['transfer_limit'] = $transfer_limit;
        $orderData['remark_fail'] = '车辆报告有效期内重拍';
        $carData['car_status'] = '7';
        $carData['re_auction_type'] = 3;
        $carData['is_self_receive'] = 0;
        //保留价更改
        if ($car_detail['reserve_price'] != $reserve_price) {
            $carData['reserve_price'] = $reserve_price;
            //记录修改历史
            $reserve_price_history = json_decode($car_detail['reserve_price_history']);
            array_push($reserve_price_history, array(
                'price' => $reserve_price,
                'name' => $this->user_info['real_name'],
                'id' => $this->user_info['emp_id'],
                'time' => date("Y-m-d H:i:s")
            ));
            $carData['reserve_price_history'] = json_encode($reserve_price_history, JSON_UNESCAPED_UNICODE);
        }
        //开启事务
        M()->startTrans();
        $res = $order->update($orderData);
        $res1 = $car->update($carData);
        $data = array();
        $data['order_id'] = $order_id;
        $data['owner_id'] = $owner_id;
        $data['service_id'] = $this->emp_id;
        $data['remark'] = urldecode($remark_fail);
        $data['result'] = '5'; //重拍
        $owner = new Owner($owner_id);
        $res2 = $owner->confirm_trace_log($data);

        if (!$res || !$res1 || !$res2) {
            M()->rollback();
            $this->helpJsonResult(500, "操作失败或数据已更新未改变");
        }
        //提交事务
        M()->commit();

        //解冻车商保证金
        AssetCenter::free_all($order_id);

        //更新车源状态
        $CarSource = new CarSource($car_detail['sid']);
        $CarSourceInfo = $CarSource->getInfo();
        if ($CarSourceInfo['status'] == 600) {
            $csData = [];
            $csData['status'] = 100;
            $res_cs = $CarSource->update($csData);
        }
        //双方磋商跟踪日志
        $consult_trace_log = array(
            'order_id' => $order_id,
            'emp_id' => $this->emp_id,
            'action' => '磋商失败重拍',
            'type' => 2,
            'result' => $remark_fail,
        );
        $this->Consult->add_consult_trace_log($consult_trace_log);

        //记录车主确认的拍单重拍记录
        $owner_remake_log = array(
            'emp_id' => $this->emp_id,
            'owner_id' => $owner_id,
            'car_id' => $car_detail['car_id'],
            'order_id' => $order_id,
            'reserve_price' => $reserve_price,
            'last_transfer_limit' => $last_transfer_limit,
            'transfer_limit' => $transfer_limit,
            'remark' => $remark_fail
        );
        \AuctionCore\AuctionOrder\AuOrder::add_owner_remake_log($owner_remake_log);

        //记录车辆全局跟踪日志
        \AuctionCore\System\GlobalLog::add([
                'emp_id' => $this->emp_id,
                'order_id' => $order_id,
                'car_id' => $order_detail['car_id'],
                'owner_id' => $owner_id,
                'result' => '双方磋商失败车辆重拍']
        );

        //记录车辆跟踪日志
        Car::add_car_trace_log($order_detail['car_id'], [
            'action_name' => "双方磋商失败，重拍",
            'emp_id' => $this->emp_id
        ]);
        /**
         * 记录拍品跟踪日志
         * 磋商失败，重拍时不记录拍单日志
         */
        if ($order_detail['status'] != 12 && $order_detail['fail_type'] != 6) {
            \AuctionCore\AuctionOrder\AuOrder::add_order_trace_log($order_id, [
                'action_name' => "拍单失败",
                'emp_id' => $this->emp_id
            ]);
        }

        //记录员工操作日志
        \AuctionCore\System\SystemLog::add([
            'emp_id' => $this->emp_id,
            'order_id' => $order_id,
            'car_id' => $order_detail['car_id'],
            'owner_id' => $owner_id,
            'action' => '双方磋商失败重拍车源'
        ]);
        //输出json格式处理结果
        $this->helpJsonResult(200, "操作成功");

    }


    //处理继续跟踪
    public function do_continue_trace()
    {
        $consult_id = I('post.consult_id');
        $order_id = I('post.order_id');
        $owner_id = I('post.owner_id');
        $next_trace_time = I('post.next_trace_time');
        $next_trace_time = transform_date($next_trace_time, 2);
        $next_trace_remark = urldecode(I('post.next_trace_remark'));
        //数据验证
        if (!$order_id) {
            $this->helpJsonResult(400, "拍单ID不能为空");
        }
        $order = new AuOrder($order_id);
        $order_detail = $order->detail();
        if (empty($order_detail)) {
            $this->helpJsonResult(400, "未找到拍单信息");
        }
        if (!$owner_id) {
            $this->helpJsonResult(400, "车主ID不能为空");
        }
        if (!$next_trace_time) {
            $this->helpJsonResult(400, "下次跟踪时间不能为空");
        }
        //插入下次跟踪记录
        $data = array();
        $data['order_id'] = $order_id;
        $data['service_id'] = $this->emp_id;
        $data['next_trace_time'] = $next_trace_time;
        $data['remark'] = urldecode($next_trace_remark);
        $data['result'] = 2;
        $owner = new \AuctionCore\CarOwner\Owner($owner_id);
        $res = $owner->confirm_trace_log($data);
        if (!$res) {
            $this->helpJsonResult("跟踪记录失败,请联系管理员");
        }
        $res1 = $owner->update(array('next_trace_time' => $next_trace_time));
        if (!$res1) {
            $this->helpJsonResult(400, "更新数据失败,请联系管理员");
        }

        //更新consult
        $consult_data = array();
        $consult_data['id'] = $consult_id;
        $consult_data['emp_id'] = $this->emp_id;
        $consult_data['consult_status'] = 2; //继续跟踪
        $consult_data['consult_remark'] = $next_trace_remark;
        $consult_data['updatetime'] = date("Y-m-d H:i:s", time());
        $consult_data['next_trace_time'] = date("Y-m-d H:i:s", time());
        $res2 = $this->Consult->update_consult($consult_data);
        if (!$res2) {
            $this->helpJsonResult(400, "更新数据失败,请联系管理员");
        }
        //双方磋商跟踪日志
        $consult_trace_log = array(
            'order_id' => $order_id,
            'emp_id' => $this->emp_id,
            'action' => '继续跟踪',
            'type' => 3,
            'result' => $next_trace_remark,
        );
        $this->Consult->add_consult_trace_log($consult_trace_log);


        //记录员工操作日志
        $log = array(
            'emp_id' => $this->emp_id,
            'order_id' => $order_id,
            'car_id' => $order_detail['car_id'],
            'owner_id' => $owner_id,
            'action' => '双方磋商继续跟踪'
        );
        \AuctionCore\System\SystemLog::add($log);

        /**
         * 记录车辆跟踪日志
         */
        $car_action_data = array(
            'action_name' => '双方磋商，继续跟踪',
            'emp_id' => $this->emp_id
        );
        \AuctionCore\CarResource\Car::add_car_trace_log($order_detail['car_id'], $car_action_data);
        /**
         * 记录拍品跟踪日志
         */
        $order_action_data = array(
            'action_name' => '双方磋商，继续跟踪',
            'emp_id' => $this->emp_id
        );
        \AuctionCore\AuctionOrder\AuOrder::add_order_trace_log($order_id, $order_action_data);

        $this->helpJsonResult(200, "操作成功");
    }

    //处理不卖
    public function do_not_sell()
    {
        //获取外部数据
        $consult_id = I('post.consult_id');
        $order_id = I('post.order_id');
        $owner_id = I('post.owner_id');
        $remark_fail = urldecode(I('post.remark'));
        //数据验证
        if (!$order_id) {
            $this->helpJsonResult(400, '拍单ID不能为空');
        }
        $order = new AuOrder($order_id);
        $order_detail = $order->detail();
        if (empty($order_detail)) {
            $this->helpJsonResult(400, "未找到拍单信息");
        }
        if ($order_detail['status'] != 5) {
            $this->helpJsonResult(500, "拍单状态异常,请联系管理员");
        }
        if (!$owner_id) {
            $this->helpJsonResult(400, "车主ID不能为空");
        }
        if (!$remark_fail) {
            $this->helpJsonResult(400, '车主不卖的原因不能为空');
        }
        //开启事务
        M()->startTrans();

        //插入跟踪记录
        $fail_log = array();
        $fail_log['order_id'] = $order_id;
        $fail_log['service_id'] = $this->emp_id;
        $fail_log['remark'] = urldecode($remark_fail);
        $fail_log['result'] = 3;

        //更新车主
        $owner = new \AuctionCore\CarOwner\Owner($owner_id);
        $log_res = $owner->confirm_trace_log($fail_log);
        if (!$log_res) {
            M()->rollback();
            $this->helpJsonResult(500, "跟踪记录失败,请联系管理员");
        }

        //更新拍单表数据
        $res1 = $order->update(array('status' => '12', 'fail_type' => '2', 'remark_fail' => $remark_fail)); //12 拍单失败
        //更改车源状态为8（交易失败）
        $car = new \AuctionCore\CarResource\Car($order_detail['car_id']);
        $res2 = $car->update(array('car_status' => '8')); //8 交易失败
        //解冻车商保证金
        AssetCenter::free_all($order_id);
        if (!$res1 || !$res2) {
            M()->rollback();
            $this->helpJsonResult(500, "操作失败或数据已更新未改变");
        }

        //更新consult
        $consult_data = array();
        $consult_data['id'] = $consult_id;
        $consult_data['emp_id'] = $this->emp_id;
        $consult_data['consult_status'] = 5; //继续跟踪
        $consult_data['consult_remark'] = $remark_fail;
        $consult_data['updatetime'] = date("Y-m-d H:i:s", time());
        $res3 = $this->Consult->update_consult($consult_data);
        if (!$res3) {
            M()->rollback();
            $this->helpJsonResult(400, "更新数据失败,请联系管理员");
        }
        $car_detail = $car->detail();
        $CarSource = new CarSource($car_detail['sid']);
        $csData = [];
        $csData['status'] = 600;
        $res_cs = $CarSource->update($csData);
        if (!$res_cs) {
            M()->rollback();
            $this->helpJsonResult(400, "更新数据失败,请联系管理员");
        }
        //提交事务
        M()->commit();

        //双方磋商跟踪日志
        $consult_trace_log = array(
            'order_id' => $order_id,
            'emp_id' => $this->emp_id,
            'action' => '车主不卖',
            'type' => 4,
            'result' => $remark_fail,
        );
        $this->Consult->add_consult_trace_log($consult_trace_log);

        //记录车辆全局跟踪日志
        $log = array('emp_id' => $this->emp_id, 'order_id' => $order_id, 'car_id' => $order_detail['car_id'], 'owner_id' => $owner_id, 'result' => '确认成交');
        \AuctionCore\System\GlobalLog::add($log);

        //记录员工操作日志
        $log = array('emp_id' => $this->emp_id, 'order_id' => $order_id, 'car_id' => $order_detail['car_id'], 'owner_id' => $owner_id, 'action' => '车主确认继续跟踪');
        \AuctionCore\System\SystemLog::add($log);

        /**
         * 记录车辆跟踪日志
         */
        $car_action_data = array(
            'action_name' => '双方磋商，不卖',
            'emp_id' => $this->emp_id
        );
        \AuctionCore\CarResource\Car::add_car_trace_log($order_detail['car_id'], $car_action_data);
        /**
         * 记录拍品跟踪日志
         */
        $order_action_data = array(
            'action_name' => '双方磋商，不卖',
            'emp_id' => $this->emp_id
        );
        \AuctionCore\AuctionOrder\AuOrder::add_order_trace_log($order_id, $order_action_data);

        //输出json格式处理结果
        $this->helpJsonResult(200, "操作成功");

    }


    //查看双方磋商页面
    public function consult_view()
    {
        $consult_id = I('get.id/d', 0);
        $consult_status = I('get.status/d', 0);

        //检查权限
        $rules = "ShuangFangCuoShangChaKanSuoYou";
        $e = new Employee($this->user_info['username']);
        $auth = $e->check_auth($rules);
        if ($auth) {
            $consult_detail = $this->Consult->consult_detail($consult_id);
        } else {
            $consult_detail = $this->is_consult_assigned($consult_id, $consult_status, true);
        }
        if ($consult_status < 2 || empty($consult_status)) {
            $this->redirect('Consult/index', '', 1, '请求出错了');
        }
        $car_detail = \AuctionCore\CarResource\Car::getDetailWithChannel($consult_detail['car_id']);
        $this->assign('car_detail', $car_detail);

        $show_from = \AuctionCore\Other\Channel::get_from();  //获取渠道来源信息
        $this->assign('show_from', $show_from);

        $transfer_type = C('TRANSFER_LIMIT');
        $this->assign('transfer_type', $transfer_type);

        //------获取车主确认重拍日志
        $order = new AuOrder($consult_detail['order_id']);
        $owner_remake_log = $order->get_owner_remake_log($consult_detail['order_id']);
        $this->assign('owner_remake_log', $owner_remake_log);
        //双方磋商跟踪日志
        $consult_trace_log = $this->Consult->get_consult_trace_log($consult_detail['order_id']);
        $this->assign('status', $consult_status);
        $this->assign('detail', $consult_detail);
        $this->assign('consult_trace_log', $consult_trace_log);
        $this->display();
    }


}